<template>
  <div style="display: none;"></div>
</template>

<script lang="ts">
import { defineComponent, getCurrentInstance, inject, onMounted, onUnmounted } from 'vue'
import { CESIUM_REF_KEY, CesiumRef } from '@/libs/cesium/cesium-vue'
import * as Cesium from 'cesium'
import { Cartesian3 } from 'cesium'
import BorderWallMaterialProperty from '@/libs/cesium/layers/border-layer/borderWallMaterialProperty'

// 新增函数用于检查 GeoJSON 数据格式
const isValidGeoJson = (geoJson: any) => {
  return (
    geoJson.features &&
    geoJson.features.length > 0 &&
    geoJson.features[0].geometry &&
    geoJson.features[0].geometry.coordinates &&
    geoJson.features[0].geometry.coordinates.length > 0
  )
}

// 新增函数用于添加边界墙实体
const addBorderWall = (viewer: Cesium.Viewer, datasouce: Cesium.CustomDataSource, borderPos: number[][], material: any, proxy: any) => {
  const border = datasouce.entities.add({
    wall: {
      positions: Cartesian3.fromDegreesArray(borderPos.flat()),
      // 增加边界墙的最小高度，让边界墙更高
      minimumHeights: new Array(borderPos.length).fill(200),
      material: material,
      outline: true,
      // 增大边界宽度
      outlineWidth: 50,
      // 恢复为原本的颜色
      outlineColor: Cesium.Color.CYAN
    }
  })

  // 注册图层（只保留边界实体）
  viewer.jt?.layerManager.registerLayer('border-layer', {
    show: true,
    collection: datasouce,
    zIndex: 0,
    setShowCb: (isShow: boolean) => {
      border.show = isShow
    },
    instance: proxy,
    ex: borderPos
  })
}

export default defineComponent({
  name: 'border-layer',
  setup() {
    const cesiumRef = inject<CesiumRef>(CESIUM_REF_KEY)
    const viewer = cesiumRef?.viewer
    const datasouce: Cesium.CustomDataSource = new Cesium.CustomDataSource('border-wall')
    let material: any = null
    const proxy = getCurrentInstance()?.proxy

    const addGeoJson = async (geoJson: any) => {
      if (!viewer) return

      if (!isValidGeoJson(geoJson)) {
        console.error('GeoJSON 数据格式不正确')
        return
      }

      const borderPos = geoJson.features[0].geometry.coordinates[0]

      // 创建边界墙材质
      material = new BorderWallMaterialProperty(viewer, {
        trailImage: `${(window as any).resourceBaseUrl}/static/imgs/wall.png`, // 不推荐，但能绕过检查
        color: Cesium.Color.CYAN,
        duration: 1500
      })

      // 添加边界墙
      addBorderWall(viewer, datasouce, borderPos, material, proxy)
    }

    const init = async () => {
      if (!viewer) return
      viewer.dataSources.add(datasouce)
      try {
        const response = await fetch('public/static/geojson/shangshui_county.json')
        const geoJson = await response.json()
        await addGeoJson(geoJson)
      } catch (e) {
        console.error('加载 GeoJSON 失败:', e)
      }
    }

    onMounted(init)
    onUnmounted(() => {
      viewer?.dataSources.remove(datasouce)
    })

    return { setIntrude: () => {} }
  }
})
</script>
